﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Delphi.Janus.Util {
    public static class DateTimeExtension {

        public static DateTime NextBusinessDay(this DateTime source) {
            switch (source.DayOfWeek) {
                case DayOfWeek.Friday:
                case DayOfWeek.Saturday:
                    source = NextBusinessDay(source.AddDays(1));
                    break;
                default:
                    source = source.AddDays(1);
                    break;
            }
            return source;
        }

        public static DateTime PreviousBusinessDay(this DateTime source) {
            switch (source.DayOfWeek) {
                case DayOfWeek.Monday:
                case DayOfWeek.Sunday:
                    source = PreviousBusinessDay(source.AddDays(-1));
                    break;
                default:
                    source = source.AddDays(-1);
                    break;
            }
            return source;
        }

        public static DateTime NextBusinessDays(this DateTime source, int days) {
            int sign = Math.Sign(days);
            int absDays = Math.Abs(days);

            if (sign == 0) {
                return source;
            } else {
                for (int i = 0; i < absDays; ++i) {
                    if (sign > 0) {
                        source = NextBusinessDay(source);
                    } else {
                        source = PreviousBusinessDay(source);
                    }
                }
            }
            return source;
        }

        public static IEnumerable<DateTime> EachBusinessDay(this DateTime startDate, DateTime endDate) {
            for (var day = startDate.Date; day.Date <= endDate.Date; day = NextBusinessDays(day, 1)) {
                yield return day;
            }
        }

        public static bool IsWeekend(this DateTime source) {
            if(source.DayOfWeek == DayOfWeek.Saturday || source.DayOfWeek == DayOfWeek.Sunday) {
                return true;
            }
            return false;
        }

        public static bool IsWeekDay(this DateTime source) {
            return !IsWeekend(source);
        }
    }
}
